package com.avic.modules.equipment.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.avic.common.service.impl.BaseServiceImpl;
import com.avic.common.utils.QueryHelpPlus;
import com.avic.dozer.service.IGenerator;
import com.avic.exception.BadRequestException;
import com.avic.modules.equipment.domain.Equipment;
import com.avic.modules.equipment.domain.EquipmentCategory;
import com.avic.modules.equipment.domain.Station;
import com.avic.modules.equipment.domain.vo.Accept;
import com.avic.modules.equipment.domain.vo.EquipmentVo;
import com.avic.modules.equipment.service.EquipmentService;
import com.avic.modules.equipment.service.dto.EquipmentDto;
import com.avic.modules.equipment.service.dto.EquipmentQueryCriteria;
import com.avic.modules.equipment.service.mapper.EquipmentCategoryMapper;
import com.avic.modules.equipment.service.mapper.EquipmentMapper;
import com.avic.modules.equipment.service.mapper.StationMapper;
import com.avic.modules.log.domain.vo.LogEnumeration;
import com.avic.modules.log.domain.vo.LogVo;
import com.avic.modules.log.service.LogsService;
import com.avic.modules.log.utils.ContrastObjUtil;
import com.avic.modules.system.domain.*;
import com.avic.modules.system.service.DictDetailService;
import com.avic.modules.system.service.mapper.DictDetailMapper;
import com.avic.modules.system.service.mapper.SysUserMapper;
import com.avic.tools.config.bean.AvicConfigElement;
import com.avic.tools.utils.ExcelBean;
import com.avic.tools.utils.ExcelParser;
import com.avic.utils.FileUtil;
import com.avic.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author zhangzikang 设备表
 * @date 2022-08-14
 */
@Service(value = "equipmentService")
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EquipmentImpl extends BaseServiceImpl
        <EquipmentMapper, Equipment> implements EquipmentService {

    private final IGenerator generator;
    private final EquipmentMapper equipmentMapper;
    private final EquipmentCategoryMapper equipmentCategoryMapper;
    private final SysUserMapper userMapper;
    private final DictDetailMapper dictDetailMapper;
    private final LogsService logsService;
    private final AvicConfigElement avicConfigElement;
    private final DictDetailService dictDetailService;

    /**
     * 查看设备全部信息 分页
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> queryAll(EquipmentQueryCriteria criteria, Pageable pageable) {
        Set<Long> categoryId = new HashSet<>();
        categoryId.add(5L);
        categoryId.add(6L);
        categoryId.add(7L);
        QueryWrapper<Equipment> equipWrapper = new QueryWrapper<>();
        equipWrapper.eq("device_type",1);
        equipWrapper.in("equip_category_id",categoryId);
        List<Equipment> equipAll = equipmentMapper.selectList(equipWrapper);
        Set<String> all = new HashSet<>();
        for(Equipment equip:equipAll){
            all.add(equip.getId());
        }
        criteria.setIdAll(all);
        try {
            if(criteria.getAccepts()!=null){
                List<Accept> parse = JSONArray.parseArray(criteria.getAccepts(),Accept.class);
                // 设备id
                Set<String> idAll = new HashSet<>();

                QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
                for (Accept json:parse){
                    if(json.getName().equals("equipNumber")){
                        if(json.getCondition().equals("1")){
                            wrapper.notLike("equip_number",json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.like("equip_number",json.getValue());
                        }
                    }else if(json.getName().equals("equipName")) {
                        if(json.getCondition().equals("1")){
                            wrapper.notLike("equip_name", json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.like("equip_name", json.getValue());
                        }
                    }else if(json.getName().equals("stackNumber")){
                        if(json.getCondition().equals("1")){
                            wrapper.notLike("stack_number", json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.like("stack_number", json.getValue());
                        }

                    }else if(json.getName().equals("equipSonName")){
                        if(json.getCondition().equals("1")){
                            wrapper.notLike("equip_son_name",json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.like("equip_son_name",json.getValue());
                        }
                    }else if(json.getName().equals("manufacturer")){
                        if(json.getCondition().equals("1")){
                            wrapper.notLike("manufacturer",json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.like("manufacturer",json.getValue());
                        }
                    }else if(json.getName().equals("healthStatus")){
                        if(json.getCondition().equals("1")){
                            wrapper.ne("health_status", json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.eq("health_status", json.getValue());
                        }
                    }else if(json.getName().equals("assetStatus")){
                        if(json.getCondition().equals("1")){
                            wrapper.ne("asset_status", json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.eq("asset_status", json.getValue());
                        }
                    }else if(json.getName().equals("runningState")){
                        if(json.getCondition().equals("1")){
                            wrapper.ne("running_state", json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.eq("running_state", json.getValue());
                        }
                    }else if(json.getName().equals("strategy")){
                        if(json.getCondition().equals("1")){
                            wrapper.notLike("strategy", json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.like("strategy", json.getValue());
                        }

                    }else if(json.getName().equals("forecast")){
                        if(json.getCondition().equals("1")){
                            wrapper.notLike("forecast", json.getValue());
                        }else if(json.getCondition().equals("0")){
                            wrapper.like("forecast", json.getValue());
                        }
                    }else if(json.getName().equals("principalName")){
                        QueryWrapper<User> wrapper2 = new QueryWrapper<>();
                        wrapper2.like("nick_name",json.getValue());
                        List<User> user = userMapper.selectList(wrapper2);
                        Set<Long> id = new HashSet<>();
                        for(User user1:user){
                            id.add(user1.getId());
                        }
                        if(json.getCondition().equals("1")){
                            if(user.size()==0){
                                wrapper.eq("principal_id",0);
                            }else {
                                wrapper.notIn("principal_id",id);
                            }
                        }else if(json.getCondition().equals("0")){
                            if(user.size()==0){
                                wrapper.eq("principal_id",0);
                            }else {
                                wrapper.in("principal_id",id);
                            }
                        }
                    }else if(json.getName().equals("purchaseTime")){
                        if (json.getCondition().equals("2")){
                            String value = json.getValue();
                            String[] split = value.split(",", 0);
                            String start = null;
                            String end = null;
                            int sum = 0;
                            for(String spl:split){
                                if(sum==1){
                                    end = spl;
                                } else {
                                    start = spl;
                                }
                                sum ++;
                            }
                            wrapper.between("purchase_time", start,end);
                        } else if(json.getCondition().equals("1")) {
                            wrapper.notBetween("purchase_time",json.getValue()+" 00:00:00",json.getValue()+" 23:59:59").or().isNull("purchase_time");
                        } else if(json.getCondition().equals("0")) {
                            wrapper.between("purchase_time",json.getValue()+" 00:00:00",json.getValue()+" 23:59:59");
                        }
                    }
                }
                List<Equipment> equipment = equipmentMapper.selectList(wrapper);
                for(Equipment equip:equipment){
                    idAll.add(equip.getId());
                }
                if(equipment.size()==0){
                    idAll.add("没有东西");
                }
                criteria.setId(idAll);
            }
        } catch (JSONException e) {
            throw new BadRequestException("参数格式不匹配");
        }
        String order = "equip_number desc";
        getPageSort(pageable,order);
        PageInfo<Equipment> page = new PageInfo<>(queryAll(criteria));
        List<EquipmentDto> convert = generator.convert(page.getList(), EquipmentDto.class);
        for(EquipmentDto equipment:convert){
            User user = userMapper.selectById(equipment.getPrincipalId());
            User user2 = userMapper.selectById(equipment.getMaintainPersonId());
            if(user2!=null){
                equipment.setMaintainPersonId(user2.getIsDel()==0?user2.getId():null);
                equipment.setMaintainPersonName(user2.getIsDel()==0?user2.getNickName():null);
            }
            if(user!=null){
                equipment.setPrincipalId(user.getIsDel()==0?user.getId():null);
                equipment.setPrincipalName(user.getIsDel()==0?user.getNickName():null);
            }
        }
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content",convert);
        map.put("totalElements", page.getTotal());
        return map;
    }

    /**
     * 查看设备全部信息 不分页
     * @param criteria
     * @return
     */
    @Override
    public List<Equipment> queryAll(EquipmentQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(Equipment.class,criteria));
    }

    /**
     * 查询导出设备信息
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public List<Equipment> queryAlls(EquipmentQueryCriteria criteria,Pageable pageable) {
        Set<Long> categoryId = new HashSet<>();
        categoryId.add(5L);
        categoryId.add(6L);
        categoryId.add(7L);
        QueryWrapper<Equipment> equipWrapper = new QueryWrapper<>();
        equipWrapper.eq("device_type",1);
        equipWrapper.in("equip_category_id",categoryId);
        List<Equipment> equipAll = equipmentMapper.selectList(equipWrapper);
        Set<String> all = new HashSet<>();
        for(Equipment equip:equipAll){
            all.add(equip.getId());
        }
        criteria.setIdAll(all);
        if(criteria.getAccepts()!=null){
            List<Accept> parse = JSONArray.parseArray(criteria.getAccepts(),Accept.class);
            // 设备id
            Set<String> idAll = new HashSet<>();

            QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
            for (Accept json:parse){
                if(json.getName().equals("equipNumber")){
                    if(json.getCondition().equals("1")){
                        wrapper.notLike("equip_number",json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.like("equip_number",json.getValue());
                    }
                }else if(json.getName().equals("equipName")) {
                    if(json.getCondition().equals("1")){
                        wrapper.notLike("equip_name", json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.like("equip_name", json.getValue());
                    }
                }else if(json.getName().equals("stackNumber")){
                    if(json.getCondition().equals("1")){
                        wrapper.notLike("stack_number", json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.like("stack_number", json.getValue());
                    }

                }else if(json.getName().equals("equipSonName")){
                    if(json.getCondition().equals("1")){
                        wrapper.notLike("equip_son_name",json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.like("equip_son_name",json.getValue());
                    }
                }else if(json.getName().equals("manufacturer")){
                    if(json.getCondition().equals("1")){
                        wrapper.notLike("manufacturer",json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.like("manufacturer",json.getValue());
                    }
                }else if(json.getName().equals("healthStatus")){
                    if(json.getCondition().equals("1")){
                        wrapper.ne("health_status", json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.eq("health_status", json.getValue());
                    }
                }else if(json.getName().equals("assetStatus")){
                    if(json.getCondition().equals("1")){
                        wrapper.ne("asset_status", json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.eq("asset_status", json.getValue());
                    }
                }else if(json.getName().equals("runningState")){
                    if(json.getCondition().equals("1")){
                        wrapper.ne("running_state", json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.eq("running_state", json.getValue());
                    }
                }else if(json.getName().equals("strategy")){
                    if(json.getCondition().equals("1")){
                        wrapper.notLike("strategy", json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.like("strategy", json.getValue());
                    }

                }else if(json.getName().equals("forecast")){
                    if(json.getCondition().equals("1")){
                        wrapper.notLike("forecast", json.getValue());
                    }else if(json.getCondition().equals("0")){
                        wrapper.like("forecast", json.getValue());
                    }
                }else if(json.getName().equals("principalName")){
                    QueryWrapper<User> wrapper2 = new QueryWrapper<>();
                    wrapper2.like("nick_name",json.getValue());
                    List<User> user = userMapper.selectList(wrapper2);
                    Set<Long> id = new HashSet<>();
                    for(User user1:user){
                        id.add(user1.getId());
                    }
                    if(json.getCondition().equals("1")){
                        if(user.size()==0){
                            wrapper.eq("principal_id",0);
                        }else {
                            wrapper.notIn("principal_id",id);
                        }
                    }else if(json.getCondition().equals("0")){
                        if(user.size()==0){
                            wrapper.eq("principal_id",0);
                        }else {
                            wrapper.in("principal_id",id);
                        }
                    }
                }else if(json.getName().equals("purchaseTime")){
                    if (json.getCondition().equals("2")){
                        String value = json.getValue();
                        String[] split = value.split(",", 0);
                        String start = null;
                        String end = null;
                        int sum = 0;
                        for(String spl:split){
                            if(sum==1){
                                end = spl;
                            } else {
                                start = spl;
                            }
                            sum ++;
                        }
                        wrapper.between("purchase_time", start,end);
                    } else if(json.getCondition().equals("1")) {
                        wrapper.notBetween("purchase_time",json.getValue()+" 00:00:00",json.getValue()+" 23:59:59").or().isNull("purchase_time");
                    } else if(json.getCondition().equals("0")) {
                        wrapper.between("purchase_time",json.getValue()+" 00:00:00",json.getValue()+" 23:59:59");
                    }
                }
            }
            List<Equipment> equipment = equipmentMapper.selectList(wrapper);
            for(Equipment equip:equipment){
                idAll.add(equip.getId());
            }
            if(equipment.size()==0){
                idAll.add("没有东西");
            }
            criteria.setId(idAll);
        }
        String order = "equip_number desc";
        getPageSize(pageable,order);
        return baseMapper.selectList(QueryHelpPlus.getPredicate(Equipment.class,criteria));
    }

    /**
     * 导出设备台账信息
     * @param all
     * @param response
     * @throws IOException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void download(List<EquipmentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        long sum = 1;
        for (EquipmentDto equip : all) {
            User user = userMapper.selectById(equip.getPrincipalId());
            equip.setPrincipalName(user.getIsDel()==0?user.getNickName():null);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号",sum);
            map.put("设备编号",equip.getEquipNumber());
            map.put("设备类型",equip.getEquipName());
            map.put("站位", equip.getStackNumber());
            map.put("设备名称", equip.getEquipSonName());
            if(equip.getAssetStatus()==1){
                map.put("资产状态","闲置");
            }else if(equip.getAssetStatus()==2){
                map.put("资产状态","在用");
            }else if(equip.getAssetStatus()==3){
                map.put("资产状态","报废");
            } else {
                map.put("资产状态","");
            }
            map.put("生产厂家", equip.getManufacturer());
            if(equip.getPurchaseTime()!=null){
                String s = equip.getPurchaseTime().toString();
                String substring = s.substring(0, s.length() - 2);
                map.put("购入时间",substring);
            }else {
                map.put("购入时间", "");
            }
            map.put("负责人", equip.getPrincipalName());

            sum ++;
            list.add(map);
        }
        // 创建操作日志信息
        LogVo logVo = new LogVo();
        String name = "[导出]了" + "[设备台账信息]";
        logVo.setBehavior(name);
        logVo.setAction(LogEnumeration.LEADING_OUT.getMessage());
        logsService.save(logVo);
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 导出设备健康状态信息
     * @param all
     * @param response
     * @throws IOException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void export(List<EquipmentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        long sum = 1;
        for (EquipmentDto equip : all) {
            User user = userMapper.selectById(equip.getPrincipalId());
            equip.setPrincipalName(user.getIsDel()==0?user.getNickName():null);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号",sum);
            map.put("设备编号", equip.getEquipNumber());
            map.put("设备类型", equip.getEquipName());
            map.put("站位", equip.getStackNumber());
            map.put("设备名称", equip.getEquipSonName());
            if(equip.getHealthStatus()!=null){
                DictDetail dict = dictDetailMapper.selectDictDetailByLabel(21L,equip.getHealthStatus().toString());
                map.put("健康状态", dict!=null?dict.getLabel():null);
            }else {
                map.put("健康状态", "");
            }
            map.put("故障预测", equip.getForecast());
            map.put("维护策略", equip.getStrategy());
            map.put("负责人", equip.getPrincipalName());
            sum ++;
            list.add(map);
        }
        // 创建操作日志信息
        LogVo logVo = new LogVo();
        String name = "[导出]了" + "[设备健康状态信息]";
        logVo.setBehavior(name);
        logVo.setAction(LogEnumeration.LEADING_OUT.getMessage());
        logsService.save(logVo);
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 导出设备运行状态信息
     * @param all
     * @param response
     * @throws IOException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void FunctionExport(List<EquipmentDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        long sum = 1;
        for (EquipmentDto equip : all) {
            User user = userMapper.selectById(equip.getPrincipalId());
            equip.setPrincipalName(user.getIsDel()==0?user.getNickName():null);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号",sum);
            map.put("设备编号", equip.getEquipNumber());
            map.put("设备类型", equip.getEquipName());
            map.put("站位", equip.getStackNumber());
            map.put("设备名称", equip.getEquipSonName());
            if(equip.getRunningState()!=null){
                DictDetail details = dictDetailMapper.selectDictDetailByLabel(22L,equip.getRunningState().toString());
                map.put("运行状态", details!=null?details.getLabel():null);
            }else {
                map.put("运行状态", "");
            }


            map.put("负责人", equip.getPrincipalName());
            sum ++;
            list.add(map);
        }
        // 创建操作日志信息
        LogVo logVo = new LogVo();
        String name = "[导出]了" + "[设备运行状态信息]";
        logVo.setBehavior(name);
        logVo.setAction(LogEnumeration.LEADING_OUT.getMessage());
        logsService.save(logVo);
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 添加设备
     * @param equipment
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEquipment(Equipment equipment) {
        String replace = UUID.randomUUID().toString().replace("-", "");
        equipment.setId(replace);

        Equipment number = this.getOne(new LambdaQueryWrapper<Equipment>()
                .eq(Equipment::getEquipNumber, equipment.getEquipNumber()));
        if (number != null) {
            throw new BadRequestException("设备编号已存在");
        }
        Equipment assetCode = this.getOne(new LambdaQueryWrapper<Equipment>()
                .eq(Equipment::getAssetCode, equipment.getAssetCode()));
        if (assetCode != null) {
            throw new BadRequestException("资产编码不可重复");
        }

        Equipment name = this.getOne(new LambdaQueryWrapper<Equipment>()
                .eq(Equipment::getEquipSonName, equipment.getEquipSonName()));
        if (name != null) {
            throw new BadRequestException("设备名称已存在");
        }

        Pattern p = Pattern.compile("#(.+?)(?=)");
        Matcher matcher = p.matcher(equipment.getStackNumber());
        boolean b = matcher.find();
        if(!b){
            throw new BadRequestException("站位需要以#开头");
        }

        Long equipCategoryId = equipment.getEquipCategoryId();
        if(equipCategoryId<=4 && equipCategoryId >=1){
            QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
            wrapper.eq("equip_category_id", equipCategoryId);
            List<Equipment> equipment2 = equipmentMapper.selectList(wrapper);
            if(equipment2.size()>0){
                throw new BadRequestException("设备类型下已存在设备");
            }
            equipment.setDeviceType(1);
            equipment.setEquipSon(null);
        }else {
            if(equipCategoryId==7){
                equipment.setSort(6);
                String stackNumber = equipment.getStackNumber();
                if(stackNumber!=null && !stackNumber.equals("")){
                    EquipmentQueryCriteria queryCriteria = new EquipmentQueryCriteria();
                    queryCriteria.setEquipCategoryId(equipCategoryId);
                    queryCriteria.setStackNumber(stackNumber);
                    List<Equipment> equipment1 = queryAll(queryCriteria);
                    if(equipment1.size()>0){
                        throw new BadRequestException("液压泵下每个站位只能有一个设备");
                    }
                }
            }

            QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
            wrapper.eq("device_type",1);
            wrapper.eq("equip_category_id", equipCategoryId);
            Equipment equipment2 = equipmentMapper.selectOne(wrapper);
            equipment.setEquipSon(equipment2.getId());
            equipment.setDeviceType(2);
        }

        EquipmentCategory equipment1 = equipmentCategoryMapper.selectById(equipCategoryId);
        equipment.setEquipName(equipment1.getName());

        equipment.setIsDel(0);

        boolean matches = equipment.getContactInfo().matches("^1[3-9]\\d{9}$");
        if(!matches){
            throw new BadRequestException("请输入正确的手机号");
        }

        // 创建操作日志
        LogVo logVo = new LogVo();
        String name1 = "[添加]了"+ " [" + equipment.getEquipSonName()+ "] " + "设备台账信息";
        logVo.setBehavior(name1);
        logVo.setAction(LogEnumeration.Add_TO.getMessage());
        logsService.save(logVo);

        equipment.setCreateUserId(SecurityUtils.getUserId());
        equipmentMapper.insert(equipment);
    }

    /**
     * 修改设备
     * @param equipment
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editEquipment(Equipment equipment) {

        if(equipment.getId()==null){
            throw new BadRequestException("设备id不能为空");
        }

        Equipment number = this.getOne(new LambdaQueryWrapper<Equipment>()
                .eq(Equipment::getEquipNumber, equipment.getEquipNumber()));
        if (number != null && !equipment.getId().equals(number.getId())) {
            throw new BadRequestException("设备编号已存在");
        }

        Equipment assetCode = this.getOne(new LambdaQueryWrapper<Equipment>()
                .eq(Equipment::getAssetCode, equipment.getAssetCode()));
        if (assetCode != null && !assetCode.getId().equals(equipment.getId())) {
            throw new BadRequestException("资产编码不可重复");
        }

        Equipment name = this.getOne(new LambdaQueryWrapper<Equipment>()
                .eq(Equipment::getEquipSonName, equipment.getEquipSonName()));
        if (name != null && !equipment.getId().equals(name.getId())) {
            throw new BadRequestException("设备名称已存在");
        }

        Pattern p = Pattern.compile("#(.+?)(?=)");
        Matcher matcher = p.matcher(equipment.getStackNumber());
        boolean b = matcher.find();
        if(!b){
            throw new BadRequestException("站位需要以#开头");
        }
        Equipment equipment1 = equipmentMapper.selectById(equipment.getId());
        Long equipCategoryId = equipment.getEquipCategoryId();
        if(equipCategoryId<=4 && equipCategoryId >=1){

            QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
            wrapper.eq("equip_category_id", equipCategoryId);
            List<Equipment> equipment2 = equipmentMapper.selectList(wrapper);
            List<String> list = new ArrayList<>();
            for(Equipment equip:equipment2){
                list.add(equip.getId());
            }
            if(!list.contains(equipment.getId())){
                throw new BadRequestException("设备类型下已存在设备");
            }
            if(equipment1.getEquipSon()==null||equipment.getEquipSon().equals("")){
                equipment.setDeviceType(1);
            } else {
                equipment.setDeviceType(2);
            }

            equipment.setEquipSon(null);
        }else {
            if(equipCategoryId==7){
                equipment.setSort(6);
                String stackNumber = equipment.getStackNumber();
                if(stackNumber!=null && !stackNumber.equals("")){
                    EquipmentQueryCriteria queryCriteria = new EquipmentQueryCriteria();
                    queryCriteria.setEquipCategoryId(equipCategoryId);
                    queryCriteria.setStackNumber(stackNumber);
                    List<Equipment> equipment2 = queryAll(queryCriteria);
                    for(Equipment equip:equipment2){
                        if(!equip.getId().equals(equipment.getId())){
                            throw new BadRequestException("液压泵下每个站位只能有一个设备");
                        }
                    }
                }
            }
            QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
            wrapper.eq("device_type",1);
            wrapper.eq("equip_category_id", equipCategoryId);
            Equipment equipment2 = equipmentMapper.selectOne(wrapper);
            equipment.setEquipSon(equipment2.getId());
            equipment.setDeviceType(2);
        }

        EquipmentCategory categoryId = equipmentCategoryMapper.selectById(equipCategoryId);
        equipment.setEquipName(categoryId.getName());

        boolean matches = equipment.getContactInfo().matches("^1[3-9]\\d{9}$");
        if(!matches){
            throw new BadRequestException("请输入正确的手机号");
        }

        // 修改前
        EquipmentVo front = new EquipmentVo();
        front.setCode(equipment1.getAssetCode());
        front.setContactInfo(equipment1.getContactInfo());
        front.setEnableTime(equipment1.getEnableTime()!=null?equipment1.getEnableTime().toString():null);
        front.setEquipName(equipment1.getEquipSonName());
        front.setEquipNumber(equipment1.getEquipNumber());
        front.setEquipPos(equipment1.getEquipPos());
        front.setMaintainGroup(equipment1.getMaintainGroup());

        User user = userMapper.selectById(equipment1.getMaintainPersonId());
        front.setMaintainPersonName(user!=null?user.getNickName():"");
        front.setManufacturer(equipment1.getManufacturer());
        User user1 = userMapper.selectById(equipment1.getPrincipalId());
        front.setPrincipalName(user1.getNickName());
        front.setPurchaseTime(equipment1.getPurchaseTime()!=null?equipment1.getPurchaseTime().toString():null);
        front.setSpecNumber(equipment1.getSpecNumber());
        front.setStackNumber(equipment1.getStackNumber());
        DictDetail dictDetail = dictDetailMapper.selectDictDetailByLabel(20L, equipment1.getAssetStatus().toString());
        front.setState(dictDetail.getLabel());
        front.setStatusDesc(equipment1.getStatusDesc());
        front.setSupplierName(equipment1.getSupplierName());
        front.setType(equipment1.getEquipName());
        front.setWorkShop(equipment1.getWorkShop());

        // 修改后
        EquipmentVo after = new EquipmentVo();
        after.setCode(equipment.getAssetCode());
        after.setContactInfo(equipment.getContactInfo());
        after.setEnableTime(equipment.getEnableTime()!=null?equipment.getEnableTime().toString():null);
        after.setEquipName(equipment.getEquipSonName());
        after.setEquipNumber(equipment.getEquipNumber());
        after.setEquipPos(equipment.getEquipPos());
        after.setMaintainGroup(equipment.getMaintainGroup());

        User user2 = userMapper.selectById(equipment.getMaintainPersonId());
        after.setMaintainPersonName(user2.getNickName());
        after.setManufacturer(equipment.getManufacturer());
        User user3 = userMapper.selectById(equipment.getPrincipalId());
        after.setPrincipalName(user3.getNickName());
        after.setPurchaseTime(equipment.getPurchaseTime()!=null?equipment.getPurchaseTime().toString():null);
        after.setSpecNumber(equipment.getSpecNumber());
        after.setStackNumber(equipment.getStackNumber());
        DictDetail dictDetail2 = dictDetailMapper.selectDictDetailByLabel(20L, equipment.getAssetStatus().toString());
        after.setState(dictDetail2.getLabel());
        after.setStatusDesc(equipment.getStatusDesc());
        after.setSupplierName(equipment.getSupplierName());
        after.setType(equipment.getEquipName());
        after.setWorkShop(equipment.getWorkShop());

        // 创建操作日志
        String s = ContrastObjUtil.comparObj(after,front);
        LogVo logVo = new LogVo();
        String name2 = "[修改]了"+ " [" + equipment1.getEquipSonName() + "] " + "设备台账信息 ";
        logVo.setBehavior(name2);
        logVo.setInformation(s);
        logVo.setAction(LogEnumeration.MODIFY.getMessage());
        logsService.save(logVo);

        equipment.setUpdateUserId(SecurityUtils.getUserId());
        equipmentMapper.updateById(equipment);

    }
    /**
     * 查询所有设备
     * @param equipment
     * @return
     */
    @Override
    public List<Equipment> seeEquip(List<Equipment> equipment) {
        for(Equipment equip:equipment){
            EquipmentQueryCriteria queryCriteria = new EquipmentQueryCriteria();
            queryCriteria.setEquipSon(equip.getId());
            List<Equipment> equipment1 = queryAll(queryCriteria);
            // 站位数
            List<String> stackNumber = new ArrayList<>();
            for(Equipment all:equipment1){
                if(all.getStackNumber()!=null && !all.getStackNumber().equals("")){
                    if(!stackNumber.contains(all.getStackNumber())){
                        stackNumber.add(all.getStackNumber());
                    }
                }
                all.setEquipName(all.getEquipSonName());
            }
            List<Station> zzk = new ArrayList<>();
            for(String sta:stackNumber){
                Station station = new Station();
                station.setId(sta);
                station.setName(sta);
                zzk.add(station);
            }
            equip.setEquipmentAll(equipment1);
            equip.setStationAll(zzk);
        }
        return equipment;
    }

    /**
     * 导入设备台账信息
     * @param file
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void equipImport(MultipartFile file) {
        try {
            // 判断上传文件是否为空
            if(file==null){
                throw new BadRequestException("上传的文件不能是空的");
            }
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //获取文件后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));

            if(!suffixName.equalsIgnoreCase(".xls")&&!suffixName.equalsIgnoreCase(".xlsx")){
                throw new BadRequestException("文件格式不匹配");
            }

            // 把文件下载到默认路径
            String filePath = avicConfigElement.getAvatarLocation();
            String files = filePath + fileName;
            file.transferTo(new File(files));
            ExcelParser excelpaser = new ExcelParser(files);
            excelpaser.Read();
            Map<Integer,Integer> SheetNum = new HashMap<>();
            //设置要读取的工作表顺序号及其对应的行号
            SheetNum.put(1,1);
            List<ExcelBean> excelBeanList = excelpaser.GetExcelBean(SheetNum);
            for(ExcelBean Eb:excelBeanList){
                List<Map<Integer, Object>> rowList = Eb.getRows();
                if(rowList.size()==0){
                    throw new BadRequestException("文件不能是空的");
                }
                // 获取所以数据
                for(Map<Integer, Object> map:rowList){
                    Equipment equip = new Equipment();
                    Long userId = SecurityUtils.getUserId();
                    if(userId==null){
                        throw new BadRequestException("登录状态已过期");
                    }

                    String replace = UUID.randomUUID().toString().replace("-", "");
                    equip.setId(replace);
                    equip.setCreateUserId(userId);
                    equip.setIsDel(0);

                    // 序号
                    String serial = map.get(1).toString();
                    // 判断是否为空
                    if(serial.equals("<BLANK>")){
                        throw new BadRequestException("序号不能为空");
                    }

                    // 设备编号
                    String equipNumber = map.get(2).toString();
                    // 判断是否为空
                    if(equipNumber.equals("<BLANK>")){
                        throw new BadRequestException("序号为" + serial + "的设备编号不能为空");
                    }
                    // 查询判断当前编号是否存在
                    Equipment number = this.getOne(new LambdaQueryWrapper<Equipment>()
                            .eq(Equipment::getEquipNumber, equipNumber));
                    if(number!=null){
                        throw new BadRequestException("序号为" + serial + "的设备编号已存在");
                    }
                    equip.setEquipNumber(equipNumber);

                    // 资产编码
                    String assetCode = map.get(3).toString();
                    if(assetCode.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的资产编码不能为空");
                    }
                    // 查询判断资产编码是否存在
                    Equipment asset = this.getOne(new LambdaQueryWrapper<Equipment>()
                            .eq(Equipment::getAssetCode, assetCode));
                    if (asset != null) {
                        throw new BadRequestException("编号为" + equipNumber + "的资产编码不可重复");
                    }
                    equip.setAssetCode(assetCode);

                    // 设备名称
                    String equipSonName = map.get(4).toString();
                    if(equipSonName.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的设备名称不能为空");
                    }
                    // 查询判断设备名称是否存在
                    Equipment sonName = this.getOne(new LambdaQueryWrapper<Equipment>()
                            .eq(Equipment::getEquipSonName, equipSonName));
                    if (sonName != null) {
                        throw new BadRequestException("编号为" + equipNumber + "的设备名称不可重复");
                    }
                    equip.setEquipSonName(equipSonName);

                    // 资产状态
                    String assetStatus = map.get(5).toString();
                    if(assetStatus.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的资产状态不能为空");
                    }
                    // 查看是否有这个资产状态
                    List<DictDetail> dictDetails = dictDetailService.selectDictDetailByDictId(20L);
                    ArrayList<String> objects = new ArrayList<>();
                    int status = 0;
                    for(DictDetail dict:dictDetails){
                        if(dict.getLabel().equals(assetStatus)){
                            status = Integer.parseInt(dict.getValue());
                        }
                        objects.add(dict.getLabel());
                    }
                    if(!objects.contains(assetStatus)){
                        throw new BadRequestException("编号为" + equipNumber + "的资产状态不正确");
                    }
                    equip.setAssetStatus(status);

                    // 站位
                    String stackNumber = map.get(18).toString();
                    if(stackNumber.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的站位不能为空");
                    }
                    Pattern p = Pattern.compile("#(.+?)(?=)");
                    Matcher matcher = p.matcher(stackNumber);
                    boolean b = matcher.find();
                    if(!b){
                        throw new BadRequestException("编号为" + equipNumber + "的站位需要以#开头");
                    }
                    equip.setStackNumber(stackNumber);

                    // 设备类型
                    String type = map.get(6).toString();
                    if(type.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的设备类型不能为空");
                    }
                    QueryWrapper<EquipmentCategory> wrapper = new QueryWrapper<>();
                    wrapper.eq("name", type);
                    EquipmentCategory categories = equipmentCategoryMapper.selectOne(wrapper);
                    if(categories==null){
                        throw new BadRequestException("编号为" + equipNumber + "的设备类型不正确");
                    }
                    Long id = categories.getId();
                    if(id>=1 && id<=4){
                        QueryWrapper<Equipment> equipName = new QueryWrapper<>();
                        wrapper.eq("equip_category_id", categories.getId());
                        List<Equipment> equipment2 = equipmentMapper.selectList(equipName);
                        if(equipment2.size()>0){
                            throw new BadRequestException("编号为" + equipNumber + "的设备类型下已存在设备");
                        }
                        equip.setDeviceType(1);
                    } else {
                        if(id==7){
                            EquipmentQueryCriteria queryCriteria = new EquipmentQueryCriteria();
                            queryCriteria.setEquipCategoryId(id);
                            queryCriteria.setStackNumber(stackNumber);
                            List<Equipment> equipment1 = queryAll(queryCriteria);
                            if(equipment1.size()>0){
                                throw new BadRequestException("编号为" + equipNumber + "的液压泵下每个站位只能有一个设备");
                            }
                        }
                        QueryWrapper<Equipment> wrapper2 = new QueryWrapper<>();
                        wrapper2.eq("device_type",1);
                        wrapper2.eq("equip_category_id", id);
                        Equipment equipment = equipmentMapper.selectOne(wrapper2);
                        equip.setEquipSon(equipment.getId());
                        equip.setDeviceType(2);
                    }
                    equip.setEquipCategoryId(id);
                    equip.setEquipName(type);

                    // 状态说明
                    String statusDesc = map.get(7).toString();
                    if(!statusDesc.equals("<BLANK>")){
                        equip.setStatusDesc(statusDesc);
                    }

                    // 型号规格
                    String specNumber = map.get(8).toString();
                    if(!specNumber.equals("<BLANK>")){
                        equip.setSpecNumber(specNumber);
                    }

                    // 所属车间
                    String workShop = map.get(9).toString();
                    if(!workShop.equals("<BLANK>")){
                        equip.setWorkShop(workShop);
                    }

                    // 生产厂家
                    String manufacturer = map.get(10).toString();
                    if(!manufacturer.equals("<BLANK>")){
                        equip.setManufacturer(manufacturer);
                    }

                    // 设备位置
                    String equipPos = map.get(11).toString();
                    if(!equipPos.equals("<BLANK>")){
                        equip.setEquipPos(equipPos);
                    }

                    // 供应商
                    String supplierName = map.get(12).toString();
                    if(!supplierName.equals("<BLANK>")){
                        equip.setSupplierName(supplierName);
                    }

                    // 责任人
                    String principalName = map.get(13).toString();
                    if(principalName.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的责任人不能为空");
                    }
                    QueryWrapper<User> query = new QueryWrapper();
                    query.eq("nick_name",principalName);
                    List<User> users = userMapper.selectList(query);
                    if(users.size()==0){
                        throw new BadRequestException("没有" + principalName + "这个人请添加后从试");
                    }
                    for(User uid:users){
                        equip.setPrincipalId(uid.getId());
                        break;
                    }


                    // 购买时间
                    String purchaseTime = map.get(14).toString();
                    if(!purchaseTime.equals("<BLANK>")){
                        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
                        Date date = fmt.parse(purchaseTime);
                        Timestamp time = new Timestamp(date.getTime());
                        equip.setPurchaseTime(time);
                    }

                    // 联系方式
                    String contactInfo = map.get(15).toString();
                    if(contactInfo.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的联系方式不能为空");
                    }
                    boolean matches = contactInfo.matches("^1[3-9]\\d{9}$");
                    if(!matches){
                        throw new BadRequestException("编号为" + equipNumber + "的手机号码不正确");
                    }
                    equip.setContactInfo(contactInfo);

                    // 启用时间
                    String enableTime = map.get(16).toString();
                    if(!enableTime.equals("<BLANK>")){
                        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd");
                        Date date = fmt.parse(enableTime);
                        Timestamp time = new Timestamp(date.getTime());
                        equip.setEnableTime(time);
                    }

                    // 维护班组
                    String maintainGroup = map.get(17).toString();
                    if(!maintainGroup.equals("<BLANK>")){
                        equip.setMaintainGroup(maintainGroup);
                    }

                    // 维护人员
                    String maintainPersonName = map.get(19).toString();
                    if(maintainPersonName.equals("<BLANK>")){
                        throw new BadRequestException("编号为" + equipNumber + "的维护人不能为空");
                    }
                    QueryWrapper<User> userList = new QueryWrapper();
                    userList.eq("nick_name",maintainPersonName);
                    List<User> user = userMapper.selectList(userList);
                    if(user.size()==0){
                        throw new BadRequestException("没有" + maintainPersonName + "这个人请添加后从试");
                    }
                    for(User uid:user){
                        equip.setMaintainPersonId(uid.getId());
                        break;
                    }
                    equipmentMapper.insert(equip);
                }
            }
            excelpaser.Close();
            File file1 = new File(files);
            file1.delete();
            // 创建操作日志信息
            LogVo logVo = new LogVo();
            String name = "[导入]了" + "[设备台账信息]";
            logVo.setBehavior(name);
            logVo.setAction(LogEnumeration.IMPORT.getMessage());
            logsService.save(logVo);
        }catch (IOException e) {
            throw new BadRequestException("文件解析异常");
        } catch (NullPointerException e){
            throw new BadRequestException("参数格式不匹配");
        } catch (OfficeXmlFileException e) {
            throw new BadRequestException("文件解析错误");
        } catch (ParseException e){
            throw new BadRequestException("时间格式不匹配");
        }
    }

}
